package cn.jbooter.ctx.autoconfigure.startup;

import java.io.IOException;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.boot.env.PropertySourcesLoader;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.core.io.support.ResourcePatternResolver;

import cn.jbooter.coms.exceptions.FrameworkException;
import cn.jbooter.coms.utils.StringUtil;

/**
 * 初始化自定义配置文件到environment中
 * 
 * application中配置有spring.customer.config.locations=locationPattern
 * (多个locationPattern以逗号隔开eg:classpath:config/system.properties,config/app.properties)
 * 则寻找文件并初始化到environment中去
 *
 * @author HeJian
 */
public class CustomConfigureInitializer implements EnvironmentPostProcessor{
	private static final Logger logger = LoggerFactory.getLogger(CustomConfigureInitializer.class);
	
	/** 指定自定义配置文件位置 **/
	private static final String CUSTOM_CONFIG_LOCATIONS_KEY="spring.customer.config.locations";
	/** 自定义properties配置文件的编码 **/
	private static final String PROPERTIES_FILE_ENCODING="UTF-8";

	@Override
	public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
		String property_locations = environment.getProperty(CUSTOM_CONFIG_LOCATIONS_KEY);
		if(StringUtil.isEmpty(property_locations)) {
			return;
		}
		
		//读取相应路径下的配置文件
		String[] split = property_locations.split(",");
		if(split==null || split.length==0) {
			logger.warn("spring.customer.config.locations config is error. no resolved!");
			return ;
		}
		
		for(String locationPattern: split) {
			if(StringUtil.isEmpty(locationPattern)) continue;
			locationPattern = locationPattern.trim();
			//解析配置文件资源
			ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
			Resource[] resources = null;
			try {
				resources = resolver.getResources(locationPattern);
			} catch (IOException e) {
				e.printStackTrace();
				throw new FrameworkException("读取自定义配置文件出错,请检查spring.customer.config.locations配置!"+e.getMessage());
			}
			//将配置添加进environment
			for(Resource resource : resources) {
				PropertySourcesLoader propertiesLoader = new PropertySourcesLoader();
				try {
					PropertySource<?> ps = null;
					//解决读取properties配置文件中文乱码问题
					if(resource.getFilename().endsWith("."+"properties")) {
						EncodedResource rs = new EncodedResource(resource,PROPERTIES_FILE_ENCODING);
						Properties props = PropertiesLoaderUtils.loadProperties(rs);
						ps = new PropertiesPropertySource(resource.getDescription(), props);
					}else {
						ps = propertiesLoader.load(resource);
					}
					if(ps==null) continue;
					environment.getPropertySources().addFirst(ps);
				} catch (IOException e) {
					e.printStackTrace();
					logger.warn("load cust config file ["+resource.getFilename()+"] is failed ! cause : "+e.getMessage());
				}
			}
			
		}
	}
	

}
